package com.dormitory.management.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dormitory.management.system.entity.Loss;
import com.dormitory.management.system.enums.LossEnum;
import com.dormitory.management.system.enums.StatusEnum;
import com.dormitory.management.system.enums.UserEnum;
import com.dormitory.management.system.req.LossPersonalPageReq;
import com.dormitory.management.system.req.LossSaveReq;
import com.dormitory.management.system.req.LossUpdateReq;
import com.dormitory.management.system.resp.LossResp;
import com.dormitory.management.system.utils.FileStoreUtil;
import com.dormitory.management.system.mapper.LossMapper;
import com.dormitory.management.system.req.LossPageReq;
import com.dormitory.management.system.service.LossService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dormitory.management.system.service.UserService;
import com.dormitory.managemnet.util.utils.BeanUtil;
import com.google.errorprone.annotations.Var;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * <p>
 * 遗失物品表 服务实现类
 * </p>
 *
 * @author
 * @since 2021-12-17
 */
@Service
public class LossServiceImpl extends ServiceImpl<LossMapper, Loss> implements LossService {

    @Autowired
    private UserService userService;
    @Autowired
    private FileStoreUtil fileStoreUtil;

    @Override
    public boolean save(LossSaveReq req) {
        Loss loss = BeanUtil.copyProperties(req, Loss.class);
        if (userService.getRoleKey(req.getUserId()).equals(UserEnum.USER_HOUSEMASTER.getRoleKey())) {
            loss.setRoleId(UserEnum.USER_HOUSEMASTER.getRoleId());
            return this.baseMapper.insert(loss) > 0;
        }else if (userService.getRoleKey(req.getUserId()).equals(UserEnum.USER_STUDENT.getRoleKey())) {
            loss.setRoleId(UserEnum.USER_STUDENT.getRoleId());
            return this.baseMapper.insert(loss) > 0;
        }else
            return true;
    }

    @Override
    public String saveFile(MultipartFile file) throws IOException {
        if (file!=null) {
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
            return fileStoreUtil.uploadFile(inputStream,substring);
        }
        return "http://qniu.chengmingzhang.top/Fg1xeg_Awu3UuKhd3OBizu4FoRMm";
    }

    @Override
    public boolean delete(Long id) {
        return this.baseMapper.deleteById(id)>0;
    }

    @Override
    public boolean update(LossUpdateReq req) {
        return this.baseMapper.updateById(BeanUtil.copyProperties(req,Loss.class))>0;
    }

    @Override
    public boolean updateStatus(Long id) {
        Loss loss = this.baseMapper.selectById(id);
        if(loss.getStatus()== LossEnum.LOSS_LOOKING.getStatusId()){
            loss.setStatus(LossEnum.LOSS_FOUND.getStatusId());
        }else if (loss.getStatus()== LossEnum.LOSS_WAITING.getStatusId()){
            loss.setStatus(LossEnum.LOSS_DEFINE.getStatusId());
        }else {
            return false;
        }
        return this.baseMapper.updateById(loss)>0;
    }

    @Override
    public IPage<LossResp> getPage(LossPageReq req) {
        //学生遗失上报的列表
        QueryWrapper<LossResp> wrapperStu = new QueryWrapper<LossResp>()
                .eq("role_id", UserEnum.USER_STUDENT.getRoleId())
                .eq("l.status_id", StatusEnum.STATUS_NORMAL.getStatusId())
                .eq("s.status_id", StatusEnum.STATUS_NORMAL.getStatusId())
                .like(req.getTheme() != null, "theme", req.getTheme())
                .like(req.getName() != null, "name", req.getName())
                .like(req.getPhone() != null, "phone", req.getPhone())
                .apply(req.getGmtStart()!=null,"TO_DAYS(l.gmt_create) >= TO_DAYS('"+ DateFormatUtils.format(req.getGmtStart(), "yyyy-MM-dd HH:mm:ss")+"')")
                .apply(req.getGmtEnd()!=null,"TO_DAYS(l.gmt_create) <= TO_DAYS('"+ DateFormatUtils.format(req.getGmtEnd(), "yyyy-MM-dd HH:mm:ss")+"')");
//                .ge(req.getGmtStart() != null, "l.gmt_create", req.getGmtStart())
//                .le(req.getGmtEnd() != null, "l.gmt_end", req.getGmtEnd());
        if(req.getStatus()==null) {
            wrapperStu.eq("status", LossEnum.LOSS_LOOKING.getStatusId());
        } else {
            wrapperStu.eq("status", req.getStatus());
        }
        IPage<LossResp> stuPage = this.baseMapper.getStudentLossPage(new Page<>(req.getPageCurrent(), req.getPageSize()), wrapperStu);
        List<LossResp> stuList=stuPage.getRecords();
        //宿管遗失上报和寻物启示
        QueryWrapper<LossResp> wrapperHou = new QueryWrapper<LossResp>()
                .eq("role_id", UserEnum.USER_HOUSEMASTER.getRoleId())
                .eq("l.status_id", StatusEnum.STATUS_NORMAL.getStatusId())
                .eq("h.status_id", StatusEnum.STATUS_NORMAL.getStatusId())
                .like(req.getTheme() != null, "theme", req.getTheme())
                .like(req.getName() != null, "name", req.getName())
                .like(req.getPhone() != null, "phone", req.getPhone())
                .apply(req.getGmtStart()!=null,"TO_DAYS(l.gmt_create) >= TO_DAYS('"+ DateFormatUtils.format(req.getGmtStart(), "yyyy-MM-dd HH:mm:ss")+"')")
                .apply(req.getGmtEnd()!=null,"TO_DAYS(l.gmt_create) <= TO_DAYS('"+ DateFormatUtils.format(req.getGmtEnd(), "yyyy-MM-dd HH:mm:ss")+"')");
//                .ge(req.getGmtStart() != null, "l.gmt_create", req.getGmtStart())
//                .le(req.getGmtEnd() != null, "l.gmt_end", req.getGmtEnd());
        if(req.getStatus()==null) {
            wrapperHou.eq("status", LossEnum.LOSS_LOOKING.getStatusId())
                    .or()
                    .eq("status", LossEnum.LOSS_WAITING.getStatusId());
        } else {
            wrapperStu.eq("status", req.getStatus());
        }
        IPage<LossResp> houPage = this.baseMapper.getHousemasterLossPage(new Page<>(req.getPageCurrent(), req.getPageSize()), wrapperHou);
        List<LossResp> houList=houPage.getRecords();
        if (!stuList.isEmpty()&&!houList.isEmpty()){
            stuList.addAll(houList);
            stuPage.setTotal(stuList.size());
            stuPage.setPages(stuList.size()/ req.getPageSize());
            int start = (req.getPageCurrent() - 1) * req.getPageSize();
            int end = (start + req.getPageSize()) > stuList.size() ? stuList.size() : start + req.getPageSize();
            return stuPage.setRecords(stuList.subList(start, end));
        }else if (!stuList.isEmpty()&&houList.isEmpty()) {
            return stuPage;
        }else if (stuList.isEmpty()&&!houList.isEmpty()){
            return houPage;
        }else {
            return stuPage;
        }

    }

    @Override
    public IPage<LossResp> getPersonalPage(LossPersonalPageReq req) {
        if (userService.getRoleKey(req.getUserId()).equals(UserEnum.USER_HOUSEMASTER.getRoleKey())||userService.getRoleKey(req.getUserId()).equals(UserEnum.USER_ADMIN.getRoleKey())) {
            //学生遗失上报的列表
            IPage<LossResp> stuPage = this.baseMapper.getStudentLossPage(new Page<>(req.getPageCurrent(), req.getPageSize()), new QueryWrapper<LossResp>()
                    .eq("role_id",UserEnum.USER_STUDENT.getRoleId())
                    .eq("l.status_id", StatusEnum.STATUS_NORMAL.getStatusId())
                    .eq("s.status_id", StatusEnum.STATUS_NORMAL.getStatusId())
                    .like(req.getTheme() != null, "theme", req.getTheme())
                    .like(req.getName() != null, "name", req.getName())
                    .like(req.getPhone() != null, "phone", req.getPhone())
                    .eq(req.getStatus() != null, "status", req.getStatus())
                    .apply(req.getGmtStart()!=null,"TO_DAYS(l.gmt_create) >= TO_DAYS('"+ DateFormatUtils.format(req.getGmtStart(), "yyyy-MM-dd HH:mm:ss")+"')")
                    .apply(req.getGmtEnd()!=null,"TO_DAYS(l.gmt_create) <= TO_DAYS('"+ DateFormatUtils.format(req.getGmtEnd(), "yyyy-MM-dd HH:mm:ss")+"')"));
//                    .ge(req.getGmtStart() != null, "l.gmt_create", req.getGmtStart())
//                    .le(req.getGmtEnd() != null, "l.gmt_end", req.getGmtEnd()));
            List<LossResp> stuList=stuPage.getRecords();
            //宿管遗失上报和寻物启示
            IPage<LossResp> houPage = this.baseMapper.getHousemasterLossPage(new Page<>(req.getPageCurrent(), req.getPageSize()), new QueryWrapper<LossResp>()
                    .eq("role_id",UserEnum.USER_HOUSEMASTER.getRoleId())
                    .eq("l.status_id", StatusEnum.STATUS_NORMAL.getStatusId())
                    .eq("h.status_id", StatusEnum.STATUS_NORMAL.getStatusId())
                    .like(req.getTheme() != null, "theme", req.getTheme())
                    .like(req.getName() != null, "name", req.getName())
                    .like(req.getPhone() != null, "phone", req.getPhone())
                    .eq(req.getStatus() != null, "status", req.getStatus())
                    .apply(req.getGmtStart()!=null,"TO_DAYS(l.gmt_create) >= TO_DAYS('"+ DateFormatUtils.format(req.getGmtStart(), "yyyy-MM-dd HH:mm:ss")+"')")
                    .apply(req.getGmtEnd()!=null,"TO_DAYS(l.gmt_create) <= TO_DAYS('"+ DateFormatUtils.format(req.getGmtEnd(), "yyyy-MM-dd HH:mm:ss")+"')"));
//                    .ge(req.getGmtStart() != null, "gmt_create", req.getGmtStart())
//                    .le(req.getGmtEnd() != null, "gmt_end", req.getGmtEnd()));
            List<LossResp> houList=houPage.getRecords();
            if (!stuList.isEmpty()&&!houList.isEmpty()){
                stuList.addAll(houList);
                stuPage.setTotal(stuList.size());
                stuPage.setPages(stuList.size()/ req.getPageSize());
                int start = (req.getPageCurrent() - 1) * req.getPageSize();
                int end = (start + req.getPageSize()) > stuList.size() ? stuList.size() : start + req.getPageSize();
                return stuPage.setRecords(stuList.subList(start, end));
            }else if (!stuList.isEmpty()&&houList.isEmpty()) {
                return stuPage;
            }else if (stuList.isEmpty()&&!houList.isEmpty()){
                return houPage;
            }else {
                return stuPage;
            }
        } else if (userService.getRoleKey(req.getUserId()).equals(UserEnum.USER_STUDENT.getRoleKey())) {
            return  this.baseMapper.getStudentLossPage(new Page<>(req.getPageCurrent(), req.getPageSize()), new QueryWrapper<LossResp>()
                    .eq("role_id",UserEnum.USER_STUDENT.getRoleId())
                    .eq("user_id",req.getUserId())
                    .eq("l.status_id", StatusEnum.STATUS_NORMAL.getStatusId())
                    .eq("s.status_id", StatusEnum.STATUS_NORMAL.getStatusId())
                    .like(req.getTheme() != null, "theme", req.getTheme())
                    .like(req.getName() != null, "name", req.getName())
                    .like(req.getPhone() != null, "phone", req.getPhone())
                    .eq(req.getStatus() != null, "status", req.getStatus())
                    .apply(req.getGmtStart()!=null,"TO_DAYS(l.gmt_create) >= TO_DAYS('"+ DateFormatUtils.format(req.getGmtStart(), "yyyy-MM-dd HH:mm:ss")+"')")
                    .apply(req.getGmtEnd()!=null,"TO_DAYS(l.gmt_create) <= TO_DAYS('"+ DateFormatUtils.format(req.getGmtEnd(), "yyyy-MM-dd HH:mm:ss")+"')"));
//                    .ge(req.getGmtStart() != null, "l.gmt_create", req.getGmtStart())
//                    .le(req.getGmtEnd() != null, "l.gmt_end", req.getGmtEnd()));
        }else {
            return new Page<>();
        }
    }

}
